package com.demo.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.util.Properties;

/**
 * {@link EnvironmentPostProcessor}接口的实现类用于自定义{@link Environment},在application context刷新上下文之前。
 * <p>
 * 必须在{@code META-INF/spring.factories}中注册EnvironmentPostProcessor接口的实现类。
 * 如：
 * org.springframework.boot.env.EnvironmentPostProcessor=cn.edu.dgut.sai.config.SaiPropertiesPostProcessor
 */
public class ZhengPropertiesPostProcessor implements EnvironmentPostProcessor {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        // 读取自定义zheng.properties文件
        ClassPathResource resource = new ClassPathResource("zheng.properties");
        if (resource.exists()) {
            PropertySource<?> source = getPropertySource(resource);
            environment.getPropertySources().addLast(source);
            environment.getPropertySources().addLast(source);
        }
    }

    // 构造PropertiesPropertySource
    // Environment默认有两个属性源，JVM 与 系统环境变量。
    // 添加了 自定义的属性源后，就可以使用Environment.getProperty()获取指定属性名的属性值，Environment会查找所有注册的属性源。
    private PropertySource<?> getPropertySource(ClassPathResource resource) {
        try {
            Properties properties = new Properties();
            properties.load(resource.getInputStream());
            return new PropertiesPropertySource("zheng", properties);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
